<template>
  <a-drawer
      title="收款"
      :visible="visible"
      :destroyOnClose="true"
      width="1200px"
      :body-style="{
      height: 'calc(100% - 110px)',
      overflow: 'hidden',
      padding: '12px',
      display: 'flex',
      flexDirection: 'column',
    }"
      @close="onClose"
  >
    <a-alert type="info" v-if="!processApprove " class="mt-20">
      <template #message>
        收支流水暂未开启审批，点击”
        <span v-if="Approveis_admin" class="link" @click.stop="goSetting">配置</span>
        <span v-else class="link" style="cursor: not-allowed;">配置</span>
        “可快速设置。
      </template>
    </a-alert>
    <section
        style="height: 100%; overflow: hidden auto"
    >
      <a-card
          size="small"
          :bodyStyle="{ background: '#f7f7f7' }"
          :bordered="false"
      >
        <a-descriptions>
          <a-descriptions-item label="收款状态">
            <a-tag color="red">
              {{ billStatus }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item
              label="应收房源"
              :span="2"
              v-if="from !== 'cashier'"
          >
            {{ roomDetail.village_name }} / {{ roomDetail.build_name }} /
            {{ roomDetail.layer_name }} / {{ roomDetail.room_name }}
          </a-descriptions-item>
          <a-descriptions-item
              v-if="collectionType === 'single'"
              label="缴费次数"
              :span="3"
          >
            <span class="text-black fw-bold"> 第{{ billInfo?.sort }}次 </span>
            <span>（{{ billInfo?.period }}）</span>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>

      <a-table
          v-if="billList.length"
          :dataSource="billList"
          :columns="BILL_COLUMNS"
          :pagination="false"
          rowKey="id"
          size="small"
          bordered
          class="bill-table"
          :indentSize="0"
          :defaultExpandAllRows="true"
          :customRow="customRow"
          :loading="tableLoading"
      >
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'name'">
            <span>{{ text }}</span>
            <a-button
                type="link"
                v-if="record.showMatchFlow"
                style="margin-left: 10px; margin-right: 0; font-size: 12px"
                @click="showMatchFlowClick(record)"
            >
              匹配流水
            </a-button>
          </template>
          <template v-if="column.key === 'currentReceiveTotal'">
            <a-space v-if="Number(record.unreceivedTotal) > 0">
              <span
                  v-if="record.children"
                  class="text-success fw-bold"
                  style="width: 120px; display: inline-block"
              >
                {{ text }}
              </span>
              <a-input-number
                  v-else
                  v-model:value="record.currentReceiveTotal"
                  :precision="2"
                  @change="onCurrentReceiveChange(record)"
                  style="width: 120px"
                  placeholder="请输入"
                  :min="0"
                  :max="Number(record.unreceivedTotal)"
              />
              <a-button
                  type="primary"
                  ghost
                  size="small"
                  style="font-size: 12px; padding: 2px 4px"
                  @click="onReceiveAll(record)"
              >
                收完
              </a-button>
            </a-space>
            <span v-else> 已收完 </span>
          </template>
          <template v-if="column.key === 'income_date'">
            <span v-if="record.children || !Number(record.unreceivedTotal)">
              {{ record.income_date || "--" }}
            </span>
            <a-date-picker
                v-else
                v-model:value="record.income_date"
                :valueFormat="dateFormatStr"
                :allowClear="false"
                style="width: 130px"
            />
          </template>
          <template v-if="column.key === 'receiveTotal'">
            <span v-if="record.children" class="text-warning fw-bold">{{
                text
              }}</span>
            <span v-else>{{ text }}</span>
          </template>
          <template v-if="column.key === 'actualTotal'">
            <span v-if="record.children" class="text-warning fw-bold">{{
                text
              }}</span>
            <span v-else>{{ text }}</span>
          </template>
          <template v-if="column.key === 'unreceivedTotal'">
            <span v-if="record.children">{{ text }}</span>
            <span
                v-else
                :class="
                Number(record.unreceivedTotal) > 0 ? 'text-error fw-bold' : ''
              "
            >{{ text }}</span
            >
          </template>
          <template v-if="column.key === 'remainTotal'">
            <span v-if="record.children">{{ text }}</span>
            <span
                v-else
                :class="
                Number(record.unreceivedTotal) > 0 ? 'text-success fw-bold' : ''
              "
            >{{ text }}</span
            >
          </template>
        </template>
      </a-table>
      <div class="tips-box" v-if="incomeDateTurnoverArr.length > 1">
        <ExclamationCircleOutlined style="margin-right: 4px"/>由于入账时间不一致，将产生{{incomeDateTurnoverArr.length}}笔收支流水。
      </div>

      <a-form class="new-form mt-24">
        <a-row :gutter="[24, 24]">
          <a-col :span="24">
            <a-card
                title="优惠"
                size="small"
                :headStyle="{ background: '#f7f7f7' }"
            >
              <template #extra>
                <a-button
                    v-if="modelRef.adjust_mode === 'coupon'"
                    type="primary"
                    @click="issueCoupon"
                >
                  <template #icon>
                    <MoneyCollectOutlined/>
                  </template>
                  发放优惠券
                </a-button>
              </template>
              <a-row :gutter="36">
                <a-col :span="6">
                  <a-form-item label="优惠方式">
                    <a-select
                        v-model:value="modelRef.adjust_mode"
                        placeholder="请选择优惠方式"
                        allowClear
                    >
                      <a-select-option value="coupon">优惠券</a-select-option>
                      <a-select-option value="amount"
                      >按金额优惠
                      </a-select-option
                      >
                      <a-select-option value="scale"
                      >按比例优惠
                      </a-select-option
                      >
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item
                      label="优惠比例"
                      v-if="modelRef.adjust_mode === 'scale'"
                  >
                    <a-input-number
                        placeholder="请输入优惠比例"
                        :precision="2"
                        class="have-unit"
                        :max="99.99"
                        :min="0"
                        v-model:value="modelRef.adjust_num"
                    />
                    <span class="unit-box">%</span>
                  </a-form-item>
                  <a-form-item
                      label="优惠金额"
                      v-if="modelRef.adjust_mode === 'amount'"
                  >
                    <a-input-number
                        placeholder="请输入优惠金额"
                        :precision="2"
                        class="have-unit"
                        v-model:value="modelRef.adjust_num"
                        :min="0"
                    />
                    <span class="unit-box">元</span>
                  </a-form-item>
                  <a-form-item
                      label="优惠券名称"
                      v-if="modelRef.adjust_mode === 'coupon'"
                  >
                    <a-select
                        v-model:value="modelRef.coupon_id"
                        placeholder="请选择"
                        :options="couponList"
                        allowClear
                        @change="handleCouponChange"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-card>
          </a-col>

          <a-col :span="24">
            <a-card
                title="收款"
                size="small"
                :headStyle="{ background: '#f7f7f7' }"
            >
              <a-row :gutter="36">
                <a-col :span="6">
                  <a-form-item label="汇款方式" v-bind="validateInfos.remit_type">
                    <a-select
                        v-model:value="modelRef.remit_type"
                        placeholder="请选择"
                        :options="remitTypeList"
                        allowClear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="6" v-if="modelRef.remit_type !== 'ONLINR_PAY'">
                  <a-form-item label="流水账户">
                    <a-select
                        v-model:value="modelRef.account_id"
                        placeholder="请选择"
                        :options="accountList"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-card>
          </a-col>
        </a-row>
      </a-form>
    </section>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onClose"> 取消</a-button>
        <a-button
            type="primary"
            @click.prevent="onSubmit"
            :loading="submitLoading"
        >
          保存
        </a-button>
      </a-space>
    </div>
  </a-drawer>

  <!-- 发放优惠券 -->
  <IssueCoupon
      :visible="issueVisible"
      :showChange="false"
      :ownerInfo="ownerInfo"
      @closeModal="issueVisible = false"
      @successGrant="successGrant"
  />

  <!-- 匹配流水 -->
  <MatchTurnover
      :cost_type="currentBill.cost_type"
      :village_id="roomDetail.village_id"
      :visible="matchTurnoverVisible"
      :type="matchTurnoverType"
      :ownerInfo="ownerInfo"
      @cancel="matchTurnoverClose"
      @success="matchTurnoverSuccess"
  />

  <!--  在线支付  -->
  <OnlinePayment
      :visible="payVisible"
      :orderId="orderId"
      :qrcodeUrl="qrcodeUrl"
      @payClose="paySuccessGoBack"
      @goBack="paySuccessGoBack"
      @paySuccess="paySuccess"
  />

  <!--  收支流水详情  -->
  <TurnoverDetailDrawer
      :visible="streamVisible"
      :id="currentStreamId"
      @handleCancel="cancelStream"
  />
</template>
<script>
import {Form, message, Modal} from "ant-design-vue";
import moment from "moment";
import {defineComponent, reactive, toRefs, computed, watch} from "vue";
import request from "../../../../common/utils/request";
import store from "@/store";
import utils from "@/common/utils/utils";
import _ from "lodash";
import {MoneyCollectOutlined, ExclamationCircleOutlined} from "@ant-design/icons-vue";
import IssueCoupon from "@/views/bill/CouponManagement/modules/IssueCoupon.vue";
import MatchTurnover from "../../../bill/BillDetail/modules/MatchTurnover.vue";
import OnlinePayment from "@/components/village/modules/OnlinePayment.vue";
import TurnoverDetailDrawer from "@/views/bill/TurnoverDetail/modules/TurnoverDetailDrawer.vue";
const useForm = Form.useForm;

const dateFormatStr = "YYYY-MM-DD";

export default defineComponent({
  name: "MakeCollections",
  components: {
    TurnoverDetailDrawer,
    OnlinePayment,
    IssueCoupon,
    MoneyCollectOutlined,
    MatchTurnover,
    ExclamationCircleOutlined,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    // 租客信息 {id, name}
    ownerInfo: {
      type: Object,
      default: () => ({}),
    },
    // 房源详情
    roomDetail: {
      type: Object,
      default: () => ({}),
    },
    // 账单
    billInfo: {
      type: Object,
      default: () => ({}),
    },
    // 点击列过来的（单选）还是 多选账单过来的
    collectionType: {
      type: String,
      default: "",
    },
    // 多选的所有账单的list
    collectionsList: {
      type: Array,
      default: () => [],
    },
    // 来源
    from: {
      type: String,
      default: "",
    },
    billIds: {
      type: Array,
      default: () => [],
    }
  },
  setup(props, {emit}) {
    const state = reactive({
      billList: [],
      dateFormatStr,
      submitLoading: false,
      billStatus: "",
      remitTypeList: [],
      accountList: [],
      couponList: [], // 优惠券列表
      issueVisible: false,
      discount_amount: 0, // 优惠券优惠的值

      matchTurnoverVisible: false,
      matchTurnoverType: "bill",
      currentBill: {}, //当前选中操作的record
      billListMatched: false, //是否有账单匹配过流水
      orderId: "", // 订单id,
      payVisible: false, // 支付的展示
      qrcodeUrl: "",
      tableLoading: false,
      onlineSuccess: false,
      streamIds: [], // 收支流水id
      currentStreamId: 0,
      streamVisible: false,

      // 是否有审批
      processApprove: false,
      Approveis_admin: false,
      Approve_id: 0,
    });

    const modelRef = reactive({
      adjust_mode: undefined, // 方式
      adjust_num: "", // 比例 或者 金额
      remit_type: undefined, // 汇款方式
      account_id: undefined,
      coupon_id: undefined, // 优惠券id
    });
    const rulesRef = reactive({
      remit_type: [{
        required: true,
        message: '请选择汇款方式',
      }],
    });

    const {resetFields,validate,validateInfos,} = useForm(modelRef, rulesRef);

    // 发放优惠券
    const issueCoupon = () => {
      state.issueVisible = true;
    };

    // 发放优惠券成功
    const successGrant = () => {
      // 再次获取优惠券列表
      state.issueVisible = false;
      updateCouponList(state.billList[0]?.currentReceiveTotal || 0);
    };

    let timeout = null;
    const onCurrentReceiveChange = (record) => {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      timeout = setTimeout(() => {
        record.remainTotal = (
            Number(record.unreceivedTotal) - Number(record.currentReceiveTotal)
        ).toFixed(2);
        getTotalReceived();
      }, 600);
    };

    const onReceiveAll = (record) => {
      if (record.children) {
        for (let bill of record.children) {
          bill.currentReceiveTotal = bill.unreceivedTotal;
          bill.remainTotal = "0.00";
        }
      }
      record.currentReceiveTotal = record.unreceivedTotal;
      record.remainTotal = "0.00";
      if (!record.children) {
        getTotalReceived();
      }
    };

    const getTotalReceived = () => {
      let receive = 0;
      let ramain = 0;
      let totalBill = state.billList[0];
      for (let bill of totalBill.children) {
        receive += Number(bill.currentReceiveTotal);
        ramain += Number(bill.remainTotal);
      }
      totalBill.currentReceiveTotal = receive.toFixed(2);
      totalBill.remainTotal = ramain.toFixed(2);
    };

    // 关闭收支流水
    const cancelStream = () => {
      state.streamVisible = false;
      emit("success");
    };

    // 支付成功
    const paySuccess = () => {
      state.onlineSuccess = true;
      if (state.orderId) {
        request.get("/org", "/owner/queryOrder", {
          owner_id: props.ownerInfo.id,
          order_id: state.orderId
        }).then((res) => {
          let id = res?.order?.stream_id || 0;
          if (id) {
            state.payVisible = false;
            state.streamIds = [id];
            state.currentStreamId = id;
            state.streamVisible = true;
          }
        })
      }
    };

    const paySuccessGoBack = () => {
      state.orderId = "";
      state.qrcodeUrl = "";
      state.payVisible = false;
      if (state.onlineSuccess) {
        emit("success");
      }
    };

    const goOnlinePay = (data) => {
      state.orderId = data?.order_id;
      state.qrcodeUrl = data?.url;
      state.payVisible = true;
    };

    const getOnlineOrder = (billList) => {
      state.submitLoading = true;
      let idArr = billList.map((v) => {
        return v.id;
      });

      let payList = billList.map((v) => {
        let village_id = v?.build_bind?.village?.id;
        let build_id = v.build_id || v?.build_bind?.build[0]?.id;
        return {
          id: v.id,
          org_id: v.org_id,
          village_id: village_id,
          build_id: build_id,
          owner_id: v.owner_id,
          bill_type: v.bill_type,
          bill_amount: Number(v.currentReceiveTotal),
          receivable_payment: Number(v.unreceivedTotal), // 当前待收
          actual_retreat: utils.countSum([
            Number(v.currentReceiveTotal),
            -Number(v?.avg_discount_amount || 0),
          ]), // 本次收款
          remark: v.remark,
        };
      });
      let bill_total = Number(state.billList[0]?.currentReceiveTotal || 0);
      let discount_money = billList.reduce((acc, cur) => utils.countSum([acc, Number(cur.avg_discount_amount)]), 0);
      let params = {
        owner_id: props.ownerInfo.id,
        bill_idArr: idArr,
        bill_total: bill_total,
        build_id:
            props.from === "cashier"
                ? billList[0].build_id
                : props.roomDetail.build_id,
        discount_money: discount_money,
        pay_bill_list: payList,
      };
      if (modelRef.adjust_mode === "coupon" && modelRef.coupon_id) {
        params.coupon_id = modelRef.coupon_id;
      }
      request
          .post("/org", "/owner/unifiedOrder", params)
          .then((res) => {
            state.submitLoading = false;
            goOnlinePay(res);
          })
          .catch(() => {
            state.submitLoading = false;
          });
    };

    // 调整优惠金额
    const adjustmentAmount = (idArr, discount_money) => {
      let params = {
        bill_ids: idArr,
        adjust_price: discount_money,
        owner_id: props.ownerInfo.id,
      };
      if (modelRef.coupon_id && state.discount_amount) {
        params.coupon_id = modelRef.coupon_id;
      }
      // bill id 去掉为0 的
      return new Promise((resolve, reject) => {
        request
            .post("/org", "/owner/batchAdjustBill", params)
            .then((res) => {
              resolve(res);
            })
            .catch((err) => {
              reject(err);
            });
      });
    };

    // 分摊的金额
    const getDiscountsBill = (list, discount_money) => {
      let params = {
        bill_list: list,
        discount_money: discount_money,
      };
      if (modelRef.coupon_id && state.discount_amount) {
        params.coupon_id = modelRef.coupon_id;
      }
      return new Promise((resolve, reject) => {
        request
            .post("/org", "/owner/billAvgDiscountList", params)
            .then((res) => {
              resolve(res?.bill_list || []);
            })
            .catch((err) => {
              reject(err);
            });
      });
    };

    const onSubmit = async () => {
      
      let billList = state.billList[0].children.filter(
          (it) => Number(it.currentReceiveTotal) > 0
      );
      const billCount = billList.length;
      if (!billCount && !state.billListMatched) {
        message.warning("本次总收款金额为0，请输入至少一个账单的收款金额！");
        return;
      }
    
      // 计算出 去除保证金以后的 本次收款 总金额
      let amount = 0;
      let bills = state.billList[0]?.children || [];
      bills.forEach((v) => {
        if (!v.is_bond) {
          amount = utils.countSum([Number(v.currentReceiveTotal), amount]);
        }
      });
      if (
          modelRef.adjust_num &&
          !amount &&
          ["scale", "amount"].includes(modelRef.adjust_mode)
      ) {
        message.warning("保证金不参与优惠！");
        return;
      }
      if (
          modelRef.adjust_num &&
          modelRef.adjust_mode === "amount" &&
          amount <= modelRef.adjust_num
      ) {
        message.warning("去除保证金后优惠后的收款金额需要大于0！");
        return;
      }
      if (!modelRef.remit_type) {
        message.warning("请选择汇款方式");
        return;
      }
      state.submitLoading = true;
      let adjust_mode = modelRef.adjust_mode;
      let adjust_num = Number(modelRef.adjust_num);
      let bill_total = Number(state.billList[0]?.currentReceiveTotal || 0);
      let discount_money = 0;
      if (["scale", "amount"].includes(adjust_mode) && adjust_num) {
        discount_money =
            adjust_mode === "amount"
                ? adjust_num
                : Number((amount * (adjust_num / 100)).toFixed(2));
      }
      if (
          adjust_mode === "coupon" &&
          modelRef.coupon_id &&
          state.discount_amount
      ) {
        discount_money = state.discount_amount;
      }
      if (adjust_mode && discount_money) {
        // 获取分摊后每笔订单的分摊金额
        let _billList = await getDiscountsBill(billList, discount_money);
        billList = _.cloneDeep(_billList);
      }

      if (modelRef.remit_type === "ONLINR_PAY") {
        // 选择的是在线支付 调用获取订单号的接口
        getOnlineOrder(billList);
        return;
      }
      if (adjust_mode && discount_money) {
        let idArr = billList.map((v) => {
          return v.id;
        });
        await adjustmentAmount(idArr, discount_money);
      }
      // 相同入账时间的只生成一笔流水；
      let submitObj = {};
      billList.forEach((bill, index) => {
        if (submitObj[bill.income_date]) {
          submitObj[bill.income_date].bill_list.push({
            bill_id: bill.id,
            match_price: utils.countSum([
              Number(bill.currentReceiveTotal),
              -Number(bill?.avg_discount_amount || 0),
            ]),
          });
        } else {
          submitObj[bill.income_date] = {};
          submitObj[bill.income_date].bill_list = [
            {
              bill_id: bill.id,
              match_price: utils.countSum([
                Number(bill.currentReceiveTotal),
                -Number(bill?.avg_discount_amount || 0),
              ]),
            },
          ];
          submitObj[bill.income_date].build_bind_submit = {
            village: {},
            build: [],
            room: [],
          };
        }

        // 遍历组装build_bind数据
        if (bill.build_bind) {
          submitObj[bill.income_date].build_bind_submit.village =
              bill.build_bind.village;

          if (typeof bill.build_bind.build == "object") {
            bill.build_bind.build = [bill.build_bind.build];
          }

          bill.build_bind.build.forEach((buildItem) => {
            submitObj[bill.income_date].build_bind_submit.build.push(buildItem);
          });
          bill.build_bind.room.forEach((roomItem) => {
            submitObj[bill.income_date].build_bind_submit.room.push(roomItem);
          });
        }
      });

      if (Object.keys(submitObj).length > 0) {
        const newTurnoverMap = async () => {
          for (const key of Object.keys(submitObj)) {
            let buildObj = {};
            let buildArr = [];
            let roomObj = {};
            let roomArr = [];
            submitObj[key].build_bind_submit.build.forEach((item, index) => {
              if (!buildObj[item.id]) {
                buildArr.push(item);
                buildObj[item.id] = true;
              }
            });
            submitObj[key].build_bind_submit.build = buildArr;
            submitObj[key].build_bind_submit.room.forEach((item, index) => {
              if (!roomObj[item.id]) {
                roomArr.push(item);
                roomObj[item.id] = true;
              }
            });
            submitObj[key].build_bind_submit.room = roomArr;
            await newTurnover(key, submitObj[key])
          }
        }

        newTurnoverMap().then(() => {
          state.submitLoading = false;
          message.success("收款成功!");
          if (state.streamIds.length) {
            state.currentStreamId = state.streamIds[0];
            state.streamVisible = true;
          } else {
            emit("success");
          }
        })
      } else {
        emit("success");
      }
    };

    const newTurnover = (match_date, bills) => {
      return new Promise((resolve, reject) => {
        let params = {
          loan_type: "INCOME",
          income_date: match_date,
          owner_id: props.ownerInfo.id,
          company_name: props.ownerInfo.name || props.ownerInfo.owner_name,
          build_bind: bills.build_bind_submit,
          account_id: modelRef.account_id,
          remit_type: modelRef.remit_type,
        };
        //多笔收款时，先生成空流水，再匹配账单
        bills.bill_list.forEach((bill, index) => {
          if (index == 0) {
            params.amount = bill.match_price;
          } else {
            params.amount += bill.match_price;
          }
        });

        if( state.processApprove ){
          params.bill_list = bills.bill_list
          params.approval = state.processApprove
        }

        request.post("/org", "/bill/createStream", params).then((res) => {
          // 先生成空流水，再匹配账单
          if (res.stream_id) {
            state.streamIds.push(res.stream_id);
            if(!state.processApprove){
              request
                  .post("/org", "/stream/matchBill", {
                    stream_id: res.stream_id,
                    match_date: match_date,
                    bill_list: bills.bill_list,
                  })
                  .then((res) => {
                    resolve();
                  })
                  .catch((err) => {
                    reject();
                  });
            }else {
              resolve();
            }
          } else {
            resolve();
          }
        });
      })
    };

    const onClose = () => {
      emit("cancel");
    };

    const getBillList = () => {
      return new Promise((resolve, reject) => {
        request
            .get("/org", "/owner/ownerFinanceList", {
              owner_id: props.ownerInfo.id,
              room_id: props.roomDetail.id,
              bill_ids: props.billIds.join(","),
            })
            .then((res) => {
              let checkedBillList = [];
              res.newList.forEach((bill, index) => {
                let newBill = {
                  id: bill.id,
                  name: bill.cost_type_txt,
                  month: bill.receivable_payment_date,
                  period: `${bill.start_date}~${bill.end_date}`,
                  start: bill.start_date,
                  end: bill.end_date,
                  income_date: bill.income_date,
                  receiveLatefeeTotal: Number(bill.receivable_latefee).toFixed(
                      2
                  ),
                  receiveTotal: (
                      Number(bill.receivable_payment) +
                      Number(bill.receivable_latefee)
                  ).toFixed(2),
                  noticeStatus: bill.notice_status,
                  settleStatus: [bill.settle_status],
                  actualTotal: (
                      Number(bill.actual_payment) + Number(bill.actual_latefee)
                  ).toFixed(2),
                  build_bind: bill.build_bind,
                  owner_id: bill.owner_id,
                  bill_type: bill.bill_type,
                  cost_type: bill.cost_type,
                  org_id: bill.org_id,
                  remark: bill.remark,
                  is_bond: bill.is_bond,
                  is_forfeit: bill.is_forfeit,
                };
                if (bill.cost_type == "cost_15") {
                  newBill.receiveRentTotal = bill.receivable_payment;
                } else {
                  newBill.receiveOtherTotal = bill.receivable_payment;
                }
                checkedBillList.push(newBill);
              });
              resolve(checkedBillList);
            }).catch(() => {
          reject();
        })
      });
    }

    const getSetting = () => {
      // 获取配置
      request.get("/org", "/approval/publish/process", {
        alias: 'bill_stream_add'
      }).then((res) => {
        state.processApprove = res.info.process    //判断是否开启
        state.Approveis_admin = res.info.is_admin    //判断是否有权限
        state.Approve_id = res.info.id

        console.log(state.processApprove ,state.Approveis_admin , state.Approve_id)
      });
    };

    const goSetting = () => {
      if (window.__MICRO_APP_ENVIRONMENT__) {

        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: "审批设置",
              maskCloseable: true,
              visible: true,
              closable: true,
              width: 1200,
              bodyStyle: {padding: 0, background: '#f7f7f7', height: '100%'},
              destroyOnClose: true,
            },
            microId: "approval_ApprovalSettings",
            app: "workApproval",
            url: '/approval/ApprovalSettings',
            params: {
              id: state.Approve_id,
              isMainDrawer: true,
              closeApproval: () => {
                getSetting()
              }
            }
          },

        })
      }
    };

    const init = async () => {
      let multipleList = _.cloneDeep(props.collectionsList);
      state.tableLoading = true;
      if (props.billIds?.length) {
        let data = await getBillList();
        multipleList = _.cloneDeep(data);
      }
      // receiveTotal 实际应收  - actualTotal 已收
      if (props.collectionType === "multiple") {
        // 所有账单的应收
        let allReceiveTotal = 0;
        // 所有账单的已收
        let allActualTotal = 0;
        // 所有滞纳金
        let allReceiveLatefeeTotal = 0;
        let status = "未收款";
        multipleList.forEach((v) => {
          allReceiveTotal = (
              Number(allReceiveTotal) + Number(v.receiveTotal)
          ).toFixed(2);
          allActualTotal = (
              Number(allActualTotal) + Number(v.actualTotal)
          ).toFixed(2);
          allReceiveLatefeeTotal = (
            Number(allReceiveLatefeeTotal) + Number(v.receiveLatefeeTotal)
          ).toFixed(2);
          if (v.settleStatus[0] == 3) {
            status = "部分已收";
          }
        });
        state.billStatus = status;
        const billItem = {
          name: "总计",
          receiveTotal: allReceiveTotal,
          actualTotal: allActualTotal,
          receiveLatefeeTotal: allReceiveLatefeeTotal,
          // 待收金额
          unreceivedTotal: (
              Number(allReceiveTotal) - Number(allActualTotal)
          ).toFixed(2),
          // 当前已收
          currentReceiveTotal: "0.00",
        };
        billItem.remainTotal = billItem.unreceivedTotal;
        let showMatchFlowFlag = true;
        billItem.children = multipleList.map((item) => {
          item.unreceivedTotal = item.remainTotal = (
              Number(item.receiveTotal) - Number(item.actualTotal)
          ).toFixed(2);
          item.currentReceiveTotal = "0.00";
          item.income_date = item.income_date || moment().format(dateFormatStr);
          // 第一个未收完的账单，显示匹配流水按钮
          if (Number(item.unreceivedTotal) > 0 && showMatchFlowFlag) {
            item.showMatchFlow = true;
            item.firstMatchFlow = true;
            showMatchFlowFlag = false;
          }
          return item;
        });
        state.billList = [billItem];
      } else {
        // 根据次数来收
        const {billInfo} = props;
        console.log(billInfo)
        state.billStatus =
            billInfo?.settleStatus?.length == 1
                ? billInfo.settleStatus[0] == 3
                    ? "部分已收"
                    : "未收款"
                : "部分已收";
        const billItem = {
          ...billInfo,
          name: "总计",
          // 当前已收
          currentReceiveTotal: "0.00",
        };
        let showMatchFlowFlag = true;
        /* 去除待退款的数据 */
        let childrenData = billInfo.children.filter((v) => v.settleStatus[0] != 4);
        billItem.children = childrenData.map((item) => {
          item.unreceivedTotal = item.remainTotal = (
              Number(item.receiveTotal) - Number(item.actualTotal)
          ).toFixed(2);
          item.currentReceiveTotal = "0.00";
          item.income_date = item.income_date || moment().format(dateFormatStr);
          // 第一个未收完的账单，显示匹配流水按钮
          if (Number(item.unreceivedTotal) > 0 && showMatchFlowFlag) {
            item.showMatchFlow = true;
            item.firstMatchFlow = true;
            showMatchFlowFlag = false;
          }
          return item;
        });
        billItem.receiveTotal = billItem.children.reduce((acc, cur) => utils.countSum([acc, Number(cur.receiveTotal)]), 0); // 实际应收
        billItem.actualTotal = billItem.children.reduce((acc, cur) => utils.countSum([acc, Number(cur.actualTotal)]), 0);// 已收
        billItem.unreceivedTotal = (billItem.children.reduce((acc, cur) => utils.countSum([acc, Number(cur.unreceivedTotal)]), 0)).toFixed(2);  // 当前待收
        billItem.receiveLatefeeTotal = (billItem.children.reduce((acc, cur) => utils.countSum([acc, Number(cur.receiveLatefeeTotal)]), 0)).toFixed(2); // 滞纳金
        // 剩余待收
        billItem.remainTotal = billItem.unreceivedTotal;
        state.billList = [billItem];
      }
      state.tableLoading = false;
    };

    const reset = () => {
      resetFields();
      state.billStatus = "";
      state.remitTypeList = [];
      state.accountList = [];
      state.couponList = [];
      state.issueVisible = false;
      state.discount_amount = 0;

      state.matchTurnoverVisible = false;
      state.currentBill = {};
      state.billListMatched = false;
      /* 在线支付 */
      state.orderId = "";
      state.payVisible = false;
      state.qrcodeUrl = "";
      state.tableLoading = false;
      state.onlineSuccess = false;
      state.streamIds = [];
      state.streamVisible = false;
      state.currentStreamId = 0;
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            store.dispatch("BillInit", {no_online_way: 1}).then((data) => {
              state.remitTypeList = data.remit_money;
              if (props.from === 'detailScan') {
                // 来自账单在线支付
                modelRef.remit_type = state.remitTypeList.find((v) => v.value === 'ONLINR_PAY')?.value || undefined;
              }
            });
            //流水账户
            request.get("/org", "/bill/getAccountList", {}).then((res) => {
              state.accountList = res.list.map((item) => ({
                value: item.id,
                label: item.name,
              }));
              if (state.accountList.length) {
                modelRef.account_id = state.accountList[0].value;
              }
            });
            init();
            getSetting();
          } else {
            reset();
          }
        }
    );

    let timeoutCoupon = null;
    let currentSearchParams = {};
    const getCouponList = (params, callback) => {
      if (timeoutCoupon) {
        clearTimeout(timeoutCoupon);
        timeoutCoupon = null;
      }
      currentSearchParams = _.cloneDeep(params);
      const getResult = () => {
        request
            .post("/org", "/owner/billMatchCouponList", params)
            .then((res) => {
              if (_.isEqual(params, currentSearchParams)) {
                let result = [];
                if (res.coupon_list.length) {
                  result = res.coupon_list.map((item) => ({
                    value: item.id,
                    label: item.name,
                    ...item,
                  }));
                }
                callback(result);
              }
            });
      };
      timeoutCoupon = setTimeout(getResult, 600);
    };

    const handleCouponChange = (value, option) => {
      state.discount_amount = option.discount_amount;
    };

    const updateCouponList = (val) => {
      //val 为收款的total
      // 如果选的都是保证金的账单 则不请求优惠券列表
      let haveAmountBill = state.billList[0].children.filter(
          (it) => Number(it.currentReceiveTotal) > 0
      );
      const branch_ids = Array.from(new Set(haveAmountBill.map(item => {
        return item.org_branch_id
      })));
      if (branch_ids.length > 1) {
        //已选择的清空了
        state.couponList = [];
        modelRef.coupon_id = undefined;
        message.warn("优惠券不支持跨公司使用,如有可用优惠券，请选择同一公司的账单后使用优惠券！")
        return
      }

      if (haveAmountBill.every((v) => v.is_bond)) {
        state.couponList = [];
      } else {
        // 否则请求优惠券列表
        let bill_ids = haveAmountBill.map((v) => v.id);
        let params = {
          bill_ids: bill_ids,
          bill_total: Number(val),
          owner_id: props.ownerInfo.id,
        };
        if (branch_ids.length == 1) {
          params.org_branch_id = branch_ids[0];
        }
        getCouponList(params, (result) => {
          state.couponList = result;
        });
      }
    };

    watch(
        () => state.billList[0]?.currentReceiveTotal,
        (val) => {
          modelRef.coupon_id = undefined;
          state.discount_amount = 0;
          if (Number(val)) {
            updateCouponList(val);
          } else {
            state.couponList = [];
          }
        }
    );

    const showMatchFlowClick = (record) => {
      state.currentBill = record;
      store.dispatch("SetMADetail", {
        bill_id: record.id,
        bill_type: record.bill_type,
        amount: Number(record.unreceivedTotal), // 账单发生额
        // latefeeAmount: Number(detail.need_latefee), // 滞纳金发生额
        // receiveAmount: Number(detail.receivable_payment),
        loan_type: record.bill_type == 1 ? "INCOME" : "PAY",
        bill_type_txt: record.name,
        owner_id: record.owner_id,
      });
      state.matchTurnoverVisible = true;
    };

    // 自定义行
    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onMouseenter: () => {
          if (!record.children && Number(record.unreceivedTotal) > 0) {
            record.showMatchFlow = true;
          }
        }, // 鼠标移入行
        onMouseleave: () => {
          if (!record.firstMatchFlow) {
            record.showMatchFlow = false;
          }
        },
      };
    };

    const matchTurnoverClose = () => {
      state.currentBill = {};
      state.matchTurnoverVisible = false;
    };

    const matchTurnoverSuccess = () => {
      request
          .get("/org", "/bill/detail", {bill_id: state.currentBill.id})
          .then((res) => {
            let {detail} = res;
            state.billList[0].children.forEach((bill) => {
              if (bill.id == state.currentBill.id) {
                // 用账单金额替换表格中数据
                bill.receiveTotal = detail.receivable_payment;
                bill.actualTotal = detail.actual_payment;
                bill.unreceivedTotal = (
                    Number(detail.receivable_payment) -
                    Number(detail.actual_payment)
                ).toFixed(2);
                bill.currentReceiveTotal = "0.00";
                bill.remainTotal = (
                    Number(detail.receivable_payment) -
                    Number(detail.actual_payment)
                ).toFixed(2);

                state.billListMatched = true;
              }
            });
            matchTurnoverClose();
          });
    };

    const incomeDateTurnoverArr = computed(() => {
      let arr = [];
      let billList = state.billList[0].children.filter(
        (it) => Number(it.currentReceiveTotal) > 0
      );
      billList.forEach((bill) => {
        if (bill.income_date && !arr.includes(bill.income_date)) {
          arr.push(bill.income_date)
        }
      })
      return arr;
    })

    return {
      BILL_COLUMNS,
      ...toRefs(state),
      modelRef,
      validateInfos,
      onClose,
      onSubmit,
      onCurrentReceiveChange,
      onReceiveAll,
      issueCoupon,
      successGrant,
      handleCouponChange,
      showMatchFlowClick,
      customRow,
      matchTurnoverClose,
      matchTurnoverSuccess,
      paySuccessGoBack,
      cancelStream,
      paySuccess,
      getSetting,
      goSetting,
      incomeDateTurnoverArr,
    };
  },
});

const BILL_COLUMNS = [
  {
    title: "费用",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "实际应收",
    dataIndex: "receiveTotal",
    key: "receiveTotal",
    align: "center",
  },
  {
    title: "已收",
    dataIndex: "actualTotal",
    key: "actualTotal",
    align: "center",
  },
  {
    title: "滞纳金",
    dataIndex: "receiveLatefeeTotal",
    key: "receiveLatefeeTotal",
    align: "center",
  },
  {
    title: "当前待收",
    dataIndex: "unreceivedTotal",
    key: "unreceivedTotal",
    align: "center",
  },
  {
    title: "本次收款",
    dataIndex: "currentReceiveTotal",
    key: "currentReceiveTotal",
    align: "center",
  },
  {
    title: "剩余待收",
    dataIndex: "remainTotal",
    key: "remainTotal",
    align: "center",
  },
  {
    title: "入账时间",
    dataIndex: "income_date",
    key: "income_date",
    align: "center",
  },
];
</script>

<style lang="less" scoped>
.bill-table {
  margin-top: 20px;

  &:deep(.ant-table) {
    color: rgba(0, 0, 0, 1);
  }

  &:deep(.ant-table-row-level-1) {
    background-color: #faad1416;
  }
}

.mt-24 {
  margin-top: 24px;
}

.new-form {
  :deep(.ant-form-item) {
    margin-bottom: 0;
  }
}

.have-unit {
  width: calc(100% - 32px);
}

.unit-box {
  text-align: center;
  line-height: 30px;
  display: inline-block;
  width: 30px;
  height: 30px;
  background: #f2f2f2;
  border: 1px solid #d9d9d9;
  border-left: none;
}
.tips-box {
  padding-top: 10px;
  color: red;
}
</style>
